<template>
  <div class="station-portal">
    <!-- 顶部搜索栏 -->
    <header class="top-header">
      <div class="header-content">
        <button class="back-btn" @click="goBack">
          <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M19 12H5M12 19l-7-7 7-7"/>
          </svg>
        </button>
        
        <div class="search-wrapper">
          <SearchBox 
            ref="searchBoxRef"
            @select="handleSelect"
            @search="handleSearch"
            :placeholder="'搜索测站...'"
          />
        </div>
      </div>
    </header>

    <!-- 主内容区 -->
    <main class="main-content">
      <!-- 加载中 -->
      <div v-if="isLoading" class="loading-section">
        <div class="loading-spinner"></div>
        <span>加载中...</span>
      </div>

      <template v-else>
        <!-- 有测站时：显示测站信息 + 功能区 -->
        <template v-if="currentStation">
          <!-- 测站头部信息 -->
          <section class="station-header">
            <div class="station-icon">
              {{ getTypeIcon(currentStation.sttype) }}
            </div>
            <div class="station-main">
              <h1 class="station-name">{{ currentStation.stnm }}</h1>
              <div class="station-tags">
                <span class="tag type">{{ getStationTypeName(currentStation.sttype) }}</span>
                <span class="tag code">{{ currentStation.stcd }}</span>
                <span class="tag location" v-if="currentStation.stlc">📍 {{ currentStation.stlc }}</span>
              </div>
            </div>
            <div class="station-actions">
              <button class="action-btn" @click="handleViewMap">
                <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2">
                  <polygon points="1 6 1 22 8 18 16 22 23 18 23 2 16 6 8 2 1 6"/>
                  <line x1="8" y1="2" x2="8" y2="18"/>
                  <line x1="16" y1="6" x2="16" y2="22"/>
                </svg>
                地图
              </button>
              <button class="action-btn" @click="copyInfo">
                <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2">
                  <rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>
                  <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
                </svg>
                复制
              </button>
            </div>
          </section>

          <!-- 信息网格 -->
          <section class="info-grid">
            <!-- 位置信息 -->
            <div class="info-block">
              <div class="block-title">
                <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2">
                  <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/>
                  <circle cx="12" cy="10" r="3"/>
                </svg>
                位置
              </div>
              <div class="block-content">
                <div class="coord-row">
                  <span class="coord-item">
                    <span class="coord-label">经度</span>
                    <span class="coord-value">{{ formatCoord(currentStation.lon, 'E') }}</span>
                  </span>
                  <span class="coord-item">
                    <span class="coord-label">纬度</span>
                    <span class="coord-value">{{ formatCoord(currentStation.lat, 'N') }}</span>
                  </span>
                </div>
              </div>
            </div>

            <!-- 流域信息 -->
            <div class="info-block">
              <div class="block-title">
                <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2">
                  <path d="M2 12h4l3-9 4 18 3-9h4"/>
                </svg>
                水文
              </div>
              <div class="block-content">
                <div class="info-item" v-if="currentStation.bsnm">
                  <span class="item-label">流域</span>
                  <span class="item-value highlight">{{ currentStation.bsnm }}</span>
                </div>
                <div class="info-item" v-if="currentStation.hnnm">
                  <span class="item-label">水系</span>
                  <span class="item-value">{{ currentStation.hnnm }}</span>
                </div>
                <div class="info-item" v-if="currentStation.rvnm">
                  <span class="item-label">河流</span>
                  <span class="item-value">{{ currentStation.rvnm }}</span>
                </div>
              </div>
            </div>

            <!-- 实时数据（TODO: 接入真实数据） -->
            <div class="info-block realtime">
              <div class="block-title">
                <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2">
                  <polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/>
                </svg>
                实时数据
              </div>
              <div class="block-content">
                <div class="data-row">
                  <div class="data-item">
                    <span class="data-value">--</span>
                    <span class="data-label">水位(m)</span>
                  </div>
                  <div class="data-item">
                    <span class="data-value">--</span>
                    <span class="data-label">流量(m³/s)</span>
                  </div>
                  <div class="data-item">
                    <span class="data-value">--</span>
                    <span class="data-label">降雨(mm)</span>
                  </div>
                </div>
                <div class="data-update">数据接入中...</div>
              </div>
            </div>
          </section>

          <!-- 快捷操作 -->
          <section class="quick-ops">
            <button class="op-btn" @click="goToRainfall">
              <span class="op-icon">🌧️</span>
              <span class="op-text">降雨数据</span>
            </button>
            <button class="op-btn" @click="goToWaterLevel">
              <span class="op-icon">💧</span>
              <span class="op-text">水情数据</span>
            </button>
            <button class="op-btn" @click="goToWeatherForecast">
              <span class="op-icon">🌤️</span>
              <span class="op-text">天气预报</span>
            </button>
            <button class="op-btn" @click="goToWarning">
              <span class="op-icon">⚠️</span>
              <span class="op-text">预警设置</span>
            </button>
          </section>
        </template>

        <!-- 通用功能区（无论是否有测站都显示） -->
        <section class="section-divider" v-if="currentStation">
          <span class="divider-text">更多功能</span>
        </section>

        <!-- 快捷功能区 -->
        <QuickActions @action="handleAction" />

        <!-- 数据看板 -->
        <Dashboard @click="handleDashboardClick" />

        <!-- 推荐测站 -->
        <StationCards 
          title="推荐测站"
          @select="handleSelectStation" 
          @more="handleMoreStations"
        />

        <!-- 最近访问 -->
        <RecentVisits 
          ref="recentVisitsRef"
          @select="handleSelectStation"
        />

        <!-- 公告通知 -->
        <Announcements 
          @click="handleAnnouncementClick"
          @more="handleMoreAnnouncements"
        />
      </template>
    </main>

    <!-- 底部 -->
    <footer class="page-footer">
      <div class="footer-content">
        <span>水文信息智能检索系统</span>
        <span class="dot">·</span>
        <span>知汛科技 © 2024</span>
      </div>
    </footer>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import SearchBox from './SearchBox.vue'
import QuickActions from './components/QuickActions.vue'
import Dashboard from './components/Dashboard.vue'
import StationCards from './components/StationCards.vue'
import RecentVisits from './components/RecentVisits.vue'
import Announcements from './components/Announcements.vue'
import { getStationDetail, getStationTypeName } from './api.js'

const props = defineProps({
  stcd: String,
  name: String,
  type: String,
  q: String,
})

// Refs
const searchBoxRef = ref(null)
const recentVisitsRef = ref(null)

// State
const currentStation = ref(null)
const isLoading = ref(false)

// 站点类型图标
const typeIconMap = {
  'RR': '🏭',
  'PP': '🌧️',
  'ZZ': '📊',
  'ZQ': '📈',
  'DD': '🚧',
  'MM': '🌡️',
  'DEFAULT': '📍'
}

function getTypeIcon(type) {
  return typeIconMap[type] || typeIconMap['DEFAULT']
}

// 格式化坐标
function formatCoord(value, suffix) {
  if (!value && value !== 0) return '--'
  return `${value.toFixed(4)}°${suffix}`
}

// 加载测站详情
async function loadStationByParams() {
  if (!props.stcd) return
  
  isLoading.value = true
  try {
    currentStation.value = await getStationDetail(props.stcd)
    if (currentStation.value) {
      recentVisitsRef.value?.addVisit({
        code: props.stcd,
        name: props.name || currentStation.value.stnm
      })
    }
  } catch (error) {
    console.error('获取测站详情失败:', error)
    uni.showToast({ title: '获取详情失败', icon: 'none' })
  } finally {
    isLoading.value = false
  }
}

// 处理选择
async function handleSelect(item) {
  isLoading.value = true
  try {
    currentStation.value = await getStationDetail(item.code)
    recentVisitsRef.value?.addVisit(item)
    uni.setNavigationBarTitle({ title: item.name || '测站详情' })
  } catch (error) {
    console.error('获取详情失败:', error)
    uni.showToast({ title: '获取详情失败', icon: 'none' })
  } finally {
    isLoading.value = false
  }
}

function handleSearch(query) {
  console.log('搜索:', query)
}

function goBack() {
  uni.navigateBack({ delta: 1 })
}

// 查看地图
function handleViewMap() {
  if (!currentStation.value) return
  const s = currentStation.value
  const stnm = encodeURIComponent(s.stnm || '')
  const lat = s.lat != null ? s.lat : ''
  const lon = s.lon != null ? s.lon : ''
  uni.navigateTo({
    url: `/pages/station/map?stcd=${s.stcd}&stnm=${stnm}&lat=${lat}&lon=${lon}`
  })
}

// 复制信息
async function copyInfo() {
  if (!currentStation.value) return
  const s = currentStation.value
  const info = `${s.stnm} (${s.stcd})
类型: ${getStationTypeName(s.sttype)}
位置: ${s.stlc || '-'}
经纬度: ${s.lon}, ${s.lat}
流域: ${s.bsnm || '-'}
水系: ${s.hnnm || '-'}
河流: ${s.rvnm || '-'}`

  try {
    await navigator.clipboard.writeText(info)
    uni.showToast({ title: '已复制', icon: 'success' })
  } catch {
    uni.showToast({ title: '复制失败', icon: 'none' })
  }
}

// 跳转到降雨数据页
function goToRainfall() {
  if (!currentStation.value) return
  uni.navigateTo({
    url: `/pages/rainfall/measured?basinCode=${currentStation.value.stcd}`
  })
}

// 跳转到水情数据页
function goToWaterLevel() {
  if (!currentStation.value) return
  uni.navigateTo({
    url: `/pages/water/detail?stationCode=${currentStation.value.stcd}`
  })
}

// 跳转到天气预报
function goToWeatherForecast() {
  uni.navigateTo({
    url: '/pages/weather/forecast'
  })
}

// 跳转到预警设置
function goToWarning() {
  uni.showToast({ title: '即将开放: 预警设置', icon: 'none' })
}

function handleAction(action) {
  uni.showToast({ title: `即将开放: ${action.name}`, icon: 'none' })
}

function handleDashboardClick(stat) {
  uni.showToast({ title: `查看: ${stat.label}`, icon: 'none' })
}

function handleSelectStation(station) {
  handleSelect(station)
}

function handleMoreStations() {
  uni.showToast({ title: '即将开放: 测站列表', icon: 'none' })
}

function handleAnnouncementClick(item) {
  uni.showToast({ title: item.title, icon: 'none' })
}

function handleMoreAnnouncements() {
  uni.showToast({ title: '即将开放: 公告列表', icon: 'none' })
}

onMounted(() => {
  loadStationByParams()
})

watch(() => props.stcd, (newVal) => {
  if (newVal) loadStationByParams()
})
</script>

<style scoped>
.station-portal {
  min-height: 100vh;
  background: linear-gradient(180deg, #0f172a 0%, #1e293b 100%);
  font-family: 'PingFang SC', 'Microsoft YaHei', -apple-system, BlinkMacSystemFont, sans-serif;
}

/* 顶部 */
.top-header {
  position: sticky;
  top: 0;
  z-index: 100;
  background: rgba(15, 23, 42, 0.95);
  backdrop-filter: blur(20px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  padding: 12px 16px;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  gap: 12px;
}

.back-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  background: rgba(255, 255, 255, 0.08);
  border: none;
  border-radius: 12px;
  color: #94a3b8;
  cursor: pointer;
  transition: all 0.2s;
  flex-shrink: 0;
}

.back-btn:hover {
  background: rgba(255, 255, 255, 0.12);
  color: #f1f5f9;
}

.search-wrapper {
  flex: 1;
}

/* 主内容 */
.main-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px 16px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 测站头部 */
.station-header {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  padding: 20px;
  background: linear-gradient(135deg, rgba(0, 212, 255, 0.1) 0%, rgba(0, 102, 255, 0.05) 100%);
  border-radius: 16px;
  border: 1px solid rgba(0, 212, 255, 0.2);
}

.station-icon {
  width: 56px;
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;
  background: rgba(0, 212, 255, 0.15);
  border-radius: 14px;
  flex-shrink: 0;
}

.station-main {
  flex: 1;
  min-width: 0;
}

.station-name {
  font-size: 22px;
  font-weight: 600;
  color: #f1f5f9;
  margin: 0 0 10px;
}

.station-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag {
  padding: 4px 10px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
}

.tag.type {
  background: linear-gradient(135deg, #00d4ff 0%, #0066ff 100%);
  color: white;
}

.tag.code {
  background: rgba(255, 255, 255, 0.1);
  color: #94a3b8;
  font-family: 'Monaco', 'Consolas', monospace;
}

.tag.location {
  background: rgba(255, 255, 255, 0.08);
  color: #94a3b8;
}

.station-actions {
  display: flex;
  gap: 8px;
  flex-shrink: 0;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 14px;
  background: rgba(255, 255, 255, 0.08);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 10px;
  color: #cbd5e1;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.2s;
}

.action-btn:hover {
  background: rgba(255, 255, 255, 0.12);
  color: #f1f5f9;
}

/* 信息网格 */
.info-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

.info-block {
  padding: 16px;
  background: rgba(255, 255, 255, 0.04);
  border-radius: 14px;
  border: 1px solid rgba(255, 255, 255, 0.08);
}

.block-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  font-weight: 600;
  color: #94a3b8;
  margin-bottom: 12px;
}

.block-title svg {
  color: #00d4ff;
}

.coord-row {
  display: flex;
  gap: 20px;
}

.coord-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.coord-label {
  font-size: 11px;
  color: #64748b;
}

.coord-value {
  font-size: 14px;
  font-weight: 600;
  color: #4ade80;
  font-family: 'Monaco', 'Consolas', monospace;
}

.info-item {
  display: flex;
  justify-content: space-between;
  padding: 6px 0;
}

.info-item:not(:last-child) {
  border-bottom: 1px dashed rgba(255, 255, 255, 0.08);
}

.item-label {
  font-size: 13px;
  color: #64748b;
}

.item-value {
  font-size: 13px;
  color: #e2e8f0;
}

.item-value.highlight {
  color: #00d4ff;
  font-weight: 500;
}

.data-row {
  display: flex;
  justify-content: space-between;
}

.data-item {
  text-align: center;
}

.data-value {
  display: block;
  font-size: 20px;
  font-weight: 700;
  color: #f1f5f9;
}

.data-label {
  font-size: 11px;
  color: #64748b;
}

.data-update {
  margin-top: 10px;
  text-align: center;
  font-size: 11px;
  color: #475569;
}

/* 快捷操作 */
.quick-ops {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 12px;
}

.op-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 16px 12px;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.08);
  border-radius: 14px;
  cursor: pointer;
  transition: all 0.2s;
}

.op-btn:hover {
  background: rgba(0, 212, 255, 0.1);
  border-color: rgba(0, 212, 255, 0.3);
  transform: translateY(-2px);
}

.op-icon {
  font-size: 24px;
}

.op-text {
  font-size: 13px;
  color: #cbd5e1;
}

/* 分隔线 */
.section-divider {
  display: flex;
  align-items: center;
  gap: 16px;
  margin: 8px 0;
}

.section-divider::before,
.section-divider::after {
  content: '';
  flex: 1;
  height: 1px;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.1), transparent);
}

.divider-text {
  font-size: 13px;
  color: #475569;
}

/* 加载中 */
.loading-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 16px;
  padding: 80px 20px;
  color: #94a3b8;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid rgba(255, 255, 255, 0.1);
  border-top-color: #00d4ff;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 底部 */
.page-footer {
  padding: 32px 24px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.footer-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-size: 13px;
  color: #64748b;
}

.dot {
  opacity: 0.5;
}

/* 响应式 */
@media (max-width: 1024px) {
  .info-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .info-block.realtime {
    grid-column: span 2;
  }
}

@media (max-width: 768px) {
  .station-header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .station-icon {
    width: 48px;
    height: 48px;
    font-size: 24px;
  }
  
  .station-actions {
    margin-top: 12px;
    justify-content: flex-start;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .info-block.realtime {
    grid-column: span 1;
  }
  
  .quick-ops {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .main-content {
    padding: 16px 12px;
    gap: 16px;
  }
}
</style>
